<?php


namespace App\HttpController\Admin;

use App\Repositories\Eloquent\Admin\AdminLogModel;
use App\Repositories\Services\Node;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
use EasySwoole\Session\Session;
use EasySwoole\Template\Render;


class Sys extends Controller
{
    //系统url链接

    protected $_data_url;
    protected $_clientIp;
    protected $url;
    protected $adminId;
    protected $sysNodes;
    protected $adminItem;
    protected $_params;
    protected $_log_model;


    public function index(){}

    //action 是控制器的方法
    public function onRequest(?string $action): ?bool
    {
        $this->url = $this->request()->getUri()->getPath();
        //初始化系统 url
        $this->initUrl();
        //节点验证
        list($status,$msg,$name,$nodes,$adminItem) = Node::getInstance()->checkNode($this->_data_url['url'],$this->_data_url['method']);

        if($status != 1){
            if($status == 333){
                $this->response()->redirect($this->_data_url['login']);
            }
            $this->ajaxError(0,$msg);
            return false;

        }
        if($adminItem){
            $this->adminId = $adminItem['id'];
            $this->adminItem = $adminItem;
            //添加操作日志
            $this->opreateLog($adminItem,$name);

        }
        //得到 用户角色的权限
        $this->sysNodes = $nodes;
        //设置分页
        if($this->request()->getRequestParam('page')){
            Session::getInstance()->set('page',$this->request()->getRequestParam('page'));
        }
        if($name){
            $this->_data_url['name'] = $name;
        }
        $this->_clientIp = $this->request()->getHeaders()['x-real-ip'][0];

        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }

    public function opreateLog($adminObj,$name){
        $logItem['id_admin'] = $adminObj['id'];
        $logItem['name'] = $adminObj['name'];
        $logItem['url'] = $this->url;
        $logItem['text'] = $name;
        $logItem['param'] = json_encode($this->request()->getRequestParam());
        $_log_model = new AdminLogModel();
        $_log_model->addItem($logItem);
    }


    public function initUrl()
    {
        //系统根目录, 模块 ,控制器, 当前访问url,控制节点 当前方法,logout,请求方法、请求参数

        $url = substr($this->url,1,strlen($this->url));
        $urlItem = explode('/',$url);
        if(empty($urlItem[2])){
            $urlItem[2] = 'index';
        }
        $this->_data_url['name'] = SYS_NAME;
        $this->_data_url['static'] = SYS_DIR_STATIC;
        $this->_data_url['plug'] = SYS_DIR_PLUG;
        $this->_data_url['root'] = SYS_ROOT;
        $this->_data_url['module'] = $urlItem[0];
        $this->_data_url['controller'] = $urlItem[1];
        $this->_data_url['action'] = $urlItem[2];
        $this->_data_url['ctr'] = SYS_ROOT . $urlItem[0] . '/' . $urlItem[1];
        $this->_data_url['url'] = $urlItem[0].'/'.$urlItem[1].'/'.$urlItem[2];
        $this->_data_url['method'] = $this->request()->getMethod();
        $this->_data_url['logout'] = SYS_USER_LOGOUT;
        $this->_data_url['login'] = SYS_USER_LOGIN;
        $this->_params = $this->request()->getRequestParam();
        return $this->_data_url['login'];
    }




    // AJAX 执行成功
    public function ajaxSuccess(array $data = [],string $msg='',int $count = 0)
    {
        $res = [];
        $res['code'] = Status::CODE_OK;
        $res['msg'] = $msg ==''?Status::getReasonPhrase(200):$msg;
        $res['count'] = $count;
        $res['data'] = $data;
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->write(json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->end();
    }

    /**
     * ajax 执行失败
     */
    public function ajaxError(int $code= 0, string $msg = '')
    {

        $res = [];
        $res['code'] = $code??Status::CODE_NO_CONTENT;
        $res['msg'] = $msg ==''?Status::getReasonPhrase(Status::CODE_NO_CONTENT):$msg;
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->write(json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->end();
    }

    /**
     * @title
     * @param $path 模板路径
     * @param $data 页面参数
     * Created by PhpStorm
     * User: shanshui
     * Date: 2020/4/23
     * Time: 11:34
     */
    public function show(string $path,array $data = []){
        $this->response()->withHeader('Content-Type','text/html; charset=utf-8');
        $data = array_merge($data,['sys_url'=>$this->_data_url]);
        $data = array_merge($data,['sys_left_nodes'=>$this->sysNodes]);
        $data = array_merge($data,['sys_user'=>$this->adminItem]);
        $this->response()->write(Render::getInstance()->render($path,$data));
    }

}